import React, { Component } from 'react';
import { Tabs, Dropdown, Icon, Menu, Button } from 'antd';
import MenuPanel from '../../routes/menuPanel/menuPanel';
import styles from '../../index.less';

class TabComponent extends Component {
  constructor(props) {
    super(props);
    const { panes } = this.props.app;
    this.state = {
      activeKey: panes[0].key,
    };
  }

  componentWillReceiveProps(nextProps) {
    const { currentPane } = nextProps.app;
    this.setState({
      activeKey: currentPane.key,
    });
  }

  onChange = (activeKey) => {
    const pane = this.props.app.panes.filter(paneTmp => paneTmp.key === activeKey)[0];
    this.props.onSaveCurrentPane(pane);
    this.setState({ activeKey });
  };
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  remove = (targetKey) => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== targetKey);
    let pane;
    if (lastIndex >= 0) {
      pane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      pane = panes[lastIndex + 1];
    } else {
      pane = {};
    }
    this.props.onRemove(panes, pane);
  };

  handleRightClick = (e) => {
    const { key } = e;
    const { panes, currentPane } = this.props.app;
    if (key === 'other') {
      const newPanes = [panes[0], currentPane];
      this.props.onRemove(newPanes, currentPane);
    } else {
      const newPanes = [panes[0]];
      this.props.onRemove(newPanes, panes[0]);
    }
  };

  render() {
    const { tabpanes } = this.props;
    const closeTabs = (
      <Menu className={styles.menuCloseTabs} onClick={this.handleRightClick}>
        <Menu.Item key="other">
          关闭其他页面
        </Menu.Item>
        <Menu.Item key="all">关闭所有页面</Menu.Item>
      </Menu>
    );
    return (
      <div className={styles.menus} id="tabs">
        <Tabs
          hideAdd
          className={styles.tabs}
          onChange={this.onChange}
          activeKey={this.state.activeKey}
          type="editable-card"
          onEdit={this.onEdit}
        >
          {tabpanes}
        </Tabs>
        <div className={styles.allMenus} id="allMenus">
          <MenuPanel />
        </div>
        <div className={styles.rightMenu}>
          <Dropdown overlay={closeTabs} trigger={['click']}>
            <Button>
              <Icon type="down-square-o" />
            </Button>
          </Dropdown>
        </div>
      </div>
    );
  }
}

export default TabComponent;
